/*
 * @Description: 
 * @Date: 2022-03-09 19:04:46
 * @LastEditTime: 2022-04-03 14:28:32
 * @FilePath: \LisoSever\src\parse.c
 */
#include "parse.h"

/**
* Given a char buffer returns the parsed request headers
*/
Request *parse(char *buffer, int size, int socketFd)
{
	
	//Differant states in the state machine
	// start		‘\r'	'\r\n'	'\r\n\r'	'\r\n\r\n'
	enum
	{
		STATE_START = 0,
		STATE_CR,
		STATE_CRLF,
		STATE_CRLFCR,
		STATE_CRLFCRLF
	};

	int i = 0, state;
	size_t offset = 0;
	char ch;
	char buf[8192];
	memset(buf, 0, 8192);

	state = STATE_START;
	while (state != STATE_CRLFCRLF)
	{
		char expected = 0;

		if (i == size)
			break;

		ch = buffer[i++];
		buf[offset++] = ch;

		switch (state)
		{
		case STATE_START:
		case STATE_CRLF:
			expected = '\r';
			break;
		case STATE_CR:
		case STATE_CRLFCR:
			expected = '\n';
			break;
		default:
			state = STATE_START;
			continue;
		}

		if (ch == expected)
			state++;
		else
			state = STATE_START;
	}
	loc += i;
	//Valid End State
	if (state == STATE_CRLFCRLF)
	{
		Request *request = (Request *)malloc(sizeof(Request));
		request->header_count = 0;
		//TODO You will need to handle resizing this in parser.y
		// 设定一个容量初值，如果还是不够，就在parser.y里扩容
		request->header_capacity = 16;
		request->headers = (Request_header *)malloc(sizeof(Request_header) * request->header_capacity);
		set_parsing_options(buf, i, request);

		if (yyparse() == SUCCESS)
		{
			return request;
		}
		else
		{
			// 如果错误要回收用malloc分配的空间
			extern FILE *yyin;
			yyrestart(yyin);
			free(request->headers);
			free(request);
		}
	}
	//TODO Handle Malformed Requests
	printf("Parsing Failed\n");
	return NULL;
}